package cn.wolfcode.web.controller;

import cn.wolfcode.common.constants.CommonConstants;
import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.CommonCodeMsg;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.redis.CommonRedisKey;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import cn.wolfcode.web.sendCallback.DefaultSendCallback;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.swing.plaf.nimbus.NimbusStyle;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderInfoController {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IOrderInfoService orderInfoService;

    @GetMapping("/find")
    public Result<OrderInfo> getById(String orderNo) {
        return Result.success(orderInfoService.getById(orderNo));
    }

    public static final Map<Long, Boolean> LOCAL_STOCK_OVER_FLAG_MAP = new ConcurrentHashMap<>();

    @RequireLogin
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/doSeckill")
    public Result<String> doSeckill(Long seckillId, Integer time, @RequestHeader(CommonConstants.TOKEN_NAME) String token) {
        // 1. 检查用户是否登录, 获取登录用户对象
        UserInfo userInfo = orderInfoService.getByToken(token);
        if (userInfo == null) {
            throw new BusinessException(CommonCodeMsg.TOKEN_INVALID);
        }
        // 2. 基于秒杀商品 id 查询秒杀商品对象
        SeckillProductVo seckillProductVo = seckillProductService.queryById(seckillId);
        // 3. 当前时间是否处于秒杀活动时间范围内
        // if (! orderInfoService.validTime(seckillProductVo.getStartDate(), seckillProductVo.getTime())) {
        //     throw new BusinessException(SeckillCodeMsg.INVALID_TIME_ERROR);
        // }
        // 检查本地标识是否已经完成
        Boolean flag = LOCAL_STOCK_OVER_FLAG_MAP.get(seckillId);
        // if (flag != null && flag) {
        //     // 如果有值且为 true, 说明已经没有了库存, 直接返回没有库存
        //     throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        // }
        // 4. 查询当前用户是否已经下过单
        OrderInfo orderInfo = orderInfoService.getByUserIdAndSeckillId(userInfo.getPhone(), seckillId);
        // if (orderInfo != null) {
        //     throw new BusinessException(SeckillCodeMsg.REPEAT_SECKILL);
        // }
        // 5. 判断库存是否足够 > 0
        // if (seckillProductVo.getStockCount() <= 0) {
        //     throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        // }

        // 查询当前用户是否已经下单
        // Boolean absent = redisTemplate.opsForHash().putIfAbsent(SeckillRedisKey.SECKILL_ORDER_USER_RECORDS_HASH.getRealKey(seckillId.toString()), userInfo.getPhone().toString(), "1");
        // if (! absent) {
        //     log.warn("[秒杀功能] 当前用户已经下过订单: seckillId={}. userId={}", seckillId, userInfo.getPhone());
        //     throw new BusinessException(SeckillCodeMsg.REPEAT_SECKILL);
        // }

        // Long remainStockCount = redisTemplate.opsForHash().increment(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time.toString()), seckillId.toString(), -1);
        // if (remainStockCount < 0) {
        //     log.info("[秒杀功能] Redis 库存预减库存不足, seckillId={}. remainStockCount={}", seckillId, remainStockCount);
        //     // 标识该秒杀商品已经卖完了
        //     LOCAL_STOCK_OVER_FLAG_MAP.put(seckillId, true);
        //     // 删除用户重复下单标记
        //     redisTemplate.opsForHash().delete(SeckillRedisKey.SECKILL_ORDER_USER_RECORDS_HASH.getRealKey(seckillId.toString()), userInfo.getPhone().toString());
        //     throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        // }
        // 6. 进行下单操作
        // 6.1 库存数量 -1
        // 6.2 创建秒杀订单
        // return Result.success(orderInfoService.createOrder(userInfo.getPhone(), seckillProductVo));

        OrderMessage message = new OrderMessage(time, seckillId, token, userInfo.getPhone());
        rocketMQTemplate.asyncSend(MQConstant.ORDER_PENDING_DEST, message, new DefaultSendCallback("创建订单", message));
        return Result.success("订单id");
    }
}
